package com.xinghai.web.controller.system;

import com.sun.org.apache.bcel.internal.generic.DNEG;
import com.xinghai.common.core.domain.AjaxResult;
import com.xinghai.common.utils.DateUtils;
import com.xinghai.system.domain.QdOrder;
import com.xinghai.system.domain.QdStore;
import com.xinghai.system.domain.vo.QdStoreDataVO;
import com.xinghai.system.domain.vo.QdStoreVo;
import com.xinghai.system.service.IQdOrderService;
import com.xinghai.system.service.IQdStoreService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.xinghai.common.config.XingHaiConfig;
import com.xinghai.common.utils.StringUtils;

import java.math.BigDecimal;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 首页
 *
 * @author xinghai
 */
@RestController
public class SysIndexController
{
    /** 系统基础配置 */
    @Autowired
    private XingHaiConfig xinghaiConfig;

    @Autowired
    private IQdStoreService storeService;

    @Autowired
    private IQdOrderService orderService;

    /**
     * 访问首页，提示语
     */
    @RequestMapping("/")
    public String index()
    {
        return StringUtils.format("欢迎使用{}后台管理框架，当前版本：v{}，请通过前端地址访问。", xinghaiConfig.getName(), xinghaiConfig.getVersion());
    }

    @RequestMapping("/getAllStoreData")
    public AjaxResult getAllStoreData(String date)
    {
        Date dateTime = new Date();
        if (StringUtils.isNotEmpty(date))
        {
            dateTime = DateUtils.parseDate(date);
        }
        List<QdStore> list = storeService.list();
        Date finalDateTime = dateTime;
        List<QdStoreDataVO> collect = list.stream().map(m -> {
            QdStoreDataVO qdStoreDataVo = new QdStoreDataVO();
            BeanUtils.copyProperties(m, qdStoreDataVo);
            QdOrder qdOrder = new QdOrder();
            qdOrder.setStoreId(m.getId());
            qdOrder.setDealTime(finalDateTime);
            qdOrder.setStatus("0");
            List<QdOrder> list1 = orderService.list(qdOrder);
            BigDecimal buyAmount = list1.stream().map(QdOrder::getPrice).reduce(BigDecimal.ZERO, BigDecimal::add);
            qdStoreDataVo.setBuyAmount(buyAmount);
            BigDecimal sellAmount = list1.stream().map(QdOrder::getNewPrice).reduce(BigDecimal.ZERO, BigDecimal::add);
            qdStoreDataVo.setSellAmount(sellAmount);
            return qdStoreDataVo;
        }).sorted(Comparator.comparing(QdStoreDataVO::getBuyAmount).reversed()).collect(Collectors.toList());
        return AjaxResult.success(collect);
    }
}
